package com.googlecode.nauka.mydbplugin.editor;


import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.text.IDocument;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.editors.text.TextEditor;

import com.googlecode.nauka.mydbplugin.resulview.ResultView;

public class SQLEditor extends TextEditor{
    public static final String ID = SQLEditor.class.getName();
    private Action             action;

    public SQLEditor(){
        setDocumentProvider(new SQLDocumentProvider());
    }

    class ExecuteQuery extends Action{
        @Override
        public void run(){
            IDocument document = getDocumentProvider().getDocument(
                getEditorInput());
            String s = document.get().trim();
            String[] ss = s.split(";");
            for(int i = 0; i < ss.length; i++){
                String query = ss[i].trim();
                if("".equals(query))
                    continue;
                try{
                    IWorkbenchPage page = PlatformUI.getWorkbench()
                        .getActiveWorkbenchWindow().getActivePage();
                    ResultView view = (ResultView)page.showView(ResultView.ID,
                        getEditorInput().getName() + "-" + (i + 1),
                        IWorkbenchPage.VIEW_CREATE
                            & IWorkbenchPage.VIEW_ACTIVATE);
                    Event event = new Event();
                    event.text = query;
                    view.getAction().runWithEvent(event);
                }catch(PartInitException e){
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void createPartControl(Composite parent){
        super.createPartControl(parent);
        action = new ExecuteQuery();
        action.setText("Execute");
        action.setToolTipText("Execute SQL query");
        action.setImageDescriptor(PlatformUI.getWorkbench().getSharedImages()
            .getImageDescriptor(ISharedImages.IMG_OBJS_INFO_TSK));
        action.setId("ExecuteQuery");
        action.setAccelerator(SWT.CTRL | 'O');
        setAction(action.getId(), action);
    }

    @Override
    protected void editorContextMenuAboutToShow(IMenuManager menu){
        super.editorContextMenuAboutToShow(menu);
        addAction(menu, "ExecuteQuery");
    }
}
